<template>
    <div class="content">
      <n-button type="info" @click="downloadCsv">导出CSV文件</n-button>
      <n-spin :show="loading" size="large">
        <n-data-table
          ref="tableRef" 
          :columns="columns"
          :data="areaList"
          :pagination="paginationReactive"
          :bordered="true"
          :scroll-x="true"
          :row-key="rowKey"
          striped
          style="margin-top: 70px; max-height: 700px;" 
          :get-csv-cell="getCsvCell"
          :get-csv-header="getCsvHeader"
        />
      </n-spin>
    </div>
  </template>
  
  <script setup>
  import { h,onMounted, reactive, ref } from 'vue';
  import { NButton, NDataTable, NSpin,NCard } from 'naive-ui';
  import axiosInstance from '@/utils/axios';
  import AMapLoader from '@amap/amap-jsapi-loader';
  
  
  const tableRef = ref(null); // 用于获取表格的ref
  
  const columns = createColumns({});
  const rowKey = (row) => row.area_id;
  const maps = reactive(new Map()); // 使用Map存储每个行的地图实例

  // 解析区域描述并返回坐标数组
const parseAreaDesc = (areaDesc) => {
  const matches = areaDesc.match(/\(([^)]+)\)/g); // 匹配所有括号中的内容
  return matches.map(coord => coord.slice(1, -1).split(',').map(Number)); // 转换为数字数组
};

  const generateContainerId = (machineId) => {
    return `container-${machineId}`;
  };
  
  // 初始化地图函数
  const initMap = (containerId,areaDesc) => {
    AMapLoader.load({
      key: "1cfd3a771aaf9dd11aa95a7472644c7e",  // API Key
      version: "2.0",  // 地图版本
      plugins: [],
    }).then((AMap) => {
      const map = new AMap.Map(containerId, {
        viewMode: "2D",   // 2D模式
        zoom: 12,         // 缩放级别
        center: ["114","30.3"],  // 初始中心位置
      });

      // 解析区域描述为坐标数组
    const path = parseAreaDesc(areaDesc);

    // 创建多边形实例
    const polygon = new AMap.Polygon({
    path, // 设置多边形的路径
    strokeColor: "#FF33FF", // 边线颜色
    strokeWeight: 2, // 边线宽度
    fillColor: "#FF99FF", // 填充颜色
    fillOpacity: 0.5, // 填充透明度
    });

    // 将多边形添加到地图
    map.add(polygon);

    // 调整地图视野以适应多边形
    map.setFitView([polygon]);

    maps.set(containerId, map);  // 存储地图实例
    }).catch((error) => {
      console.error("AMap SDK 加载失败:", error);
    });
  };
  
  // 表格列定义
  function createColumns() {
    return [
      {
        type: "expand",
        renderExpand: (rowData) => {
          const containerId = generateContainerId(rowData.area_id); // 为当前行生成唯一ID
          const areaDesc = rowData.area_desc; // 获取区域描述
          initMap(containerId,areaDesc); // 初始化地图
          return h(NCard, { id: containerId,style:{width:'100%',height:'200px'} }, h('div', {}));  // 渲染地图容器
        }
      },
      {
        title: '创建时间',
        key: 'create_time',
      },
      {
        title: '更新时间',
        key: 'update_time',
      },
      {
        title: '区域编号',
        key: 'area_id'
      },
      {
        title: '区域名称',
        key: 'area_name',
      },
    ];
  }
  
  // 表格数据（使用reactive）和分页配置
  const areaList = reactive([]);
  const maxpage = ref(0);
  const loading = ref(false);
  
  const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [3, 5, 10],
    onChange(page) {
      loading.value = true;
      if (page > paginationReactive.page && page > maxpage.value) {
        paginationReactive.page = page;
        fetchAreaList(page, paginationReactive.pageSize);
      } else {
        paginationReactive.page = page;
        loading.value = false;
      }
    },
    onUpdatePageSize(pageSize) {
      paginationReactive.pageSize = pageSize;
      paginationReactive.page = 1;
    },
  });
  
  // 获取区域列表数据
  const fetchAreaList = async () => {
    try {
      loading.value = true;
      const response = await axiosInstance.post('/api/area_list',{ page: 1 , page_size: 500 }
      );
  
      if (response.data.success) {
        areaList.length = 0
        areaList.push(...response.data.data);
        maxpage.value = Math.ceil(response.data.total / paginationReactive.pageSize);
      } else {
        console.error('没有区域数据');
      }
    } catch (error) {
      console.error('请求失败', error);
    } finally {
      loading.value = false;
    }
  };
  
  
  onMounted(() => {
    fetchAreaList();
  });
  
  // 导出CSV的函数
  const downloadCsv = () => {
    // 获取列定义
    const columnsForCsv = columns.map(col => ({
      title: col.title,
      key: col.key,
    }));
  
    // 格式化表格数据
    const dataForCsv = areaList.map(user => {
      const row = {};
      columnsForCsv.forEach(col => {
        if (col.key === 'user_status') {
          // 转换 user_status 为 可用 或 禁用
          row[col.key] = user[col.key] === 1 ? '可用' : '禁用';
        } else {
          row[col.key] = user[col.key];
        }
      });
      return row;
    });
  
    tableRef.value?.downloadCsv({
      fileName: "user-list",
      data: dataForCsv,
      columns: columnsForCsv
    });
  };
  </script>
  
  <style scoped>
  .content {
    margin-left: 60px;
    margin-top: 20px;
    height: 1000px;
    width: 1130px;
  }
  </style>
  